/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.service.pf.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.UserCache;
import com.plian.system.common.status.CheckStatus;
import com.plian.system.constant.fr.IndicatorsCodeConstant;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dto.pf.BaseBusinessProgressDTO;
import com.plian.system.entity.fr.bank.BankOrgStorage;
import com.plian.system.entity.fr.indicators.FinanceIndicators;
import com.plian.system.entity.fr.indicators.IndicatorsValue;
import com.plian.system.entity.im.BaseInvestmentExecution;
import com.plian.system.entity.im.EffectiveInvestment;
import com.plian.system.entity.im.ExecutionProjectSituation;
import com.plian.system.entity.pf.*;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.mapper.fr.indicators.FinanceIndicatorsMapper;
import com.plian.system.mapper.fr.indicators.IndicatorsValueMapper;
import com.plian.system.mapper.pf.BaseBusinessIndicatorsMapper;
import com.plian.system.mapper.pf.BaseBusinessProgressMapper;
import com.plian.system.mapper.pf.MajorProjectMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.fr.bank.IBankOrgStorageService;
import com.plian.system.service.im.IBaseInvestmentExecutionService;
import com.plian.system.service.im.IEffectiveInvestmentService;
import com.plian.system.service.im.IExecutionProjectSituationService;
import com.plian.system.service.pf.*;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pf.*;
import com.plian.system.vo.yth.YthResult;
import com.plian.system.wrapper.pf.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.ApprovalMessageTypeConstant.GZW_TYPE;
import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 经营业绩考核指标主表 服务实现类
 *
 * @author
 * @since 2019-09-27
 */
@Slf4j
@Service
@AllArgsConstructor
public class BaseBusinessProgressServiceImpl extends BaseServiceImpl<BaseBusinessProgressMapper, BaseBusinessProgress> implements IBaseBusinessProgressService, BaseFlowService {

    private FormWorkflowService formWorkflowService;

    private IFormCodeService formCodeService;

    private IBaseBusinessIndicatorsService baseBusinessIndicatorsService;

    private IAppraisalIndexService appraisalIndexService;

    private BaseBusinessProgressWrapper baseBusinessProgressWrapper;

    private IBusinessProgressService businessProgressService;

    private BusinessProgressWrapper businessProgressWrapper;

    private ITaskProgressService taskProgressService;

    private TaskProgressWrapper taskProgressWrapper;

    private ITaskIndicatorsService taskIndicatorsService;

    private FinanceIndicatorsMapper indicatorsMapper;

    private IndicatorsValueMapper indicatorsValueMapper;

    private IBankOrgStorageService bankOrgStorageService;

    private IMajorProgressService majorProgressService;

    private MajorProjectMapper majorProjectMapper;

    private BaseBusinessIndicatorsMapper baseIndicatorsMapper;

    private MajorProgressWrapper majorProgressWrapper;

    private IMainProgressService mainProgressService;

    private MainProgressWrapper mainProgressWrapper;

    private IBaseInvestmentExecutionService baseInvestmentExecutionService;

    private IEffectiveInvestmentService effectiveInvestmentService;

    private IExecutionProjectSituationService executionProjectSituationService;

    private IOrgService orgService;

    private IApprovalMessageService approvalMessageService;
    private FileService fileService;

    @Override
    public boolean saveOrUpdate(BaseBusinessProgress baseBusinessProgress) {
        baseBusinessProgress.setModuleType(0);
        if (!Optional.ofNullable(baseBusinessProgress.getStatus()).isPresent()) {
            baseBusinessProgress.setStatus(FormStatusConstant.UNREVIEWED);
        }
        if (baseBusinessProgress.getStatus().equals(FormStatusConstant.REJECT)) {
            baseBusinessProgress.setStatus(FormStatusConstant.UNREVIEWED);
        }
        if (!Optional.ofNullable(baseBusinessProgress.getId()).isPresent()) {
            baseBusinessProgress.setCode(formCodeService.getCode(FormTypeConstant.PF_BUSINESS_REPLENISH));
            baseBusinessProgress.setFormType(String.valueOf(FormTypeConstant.PF_BUSINESS_REPLENISH));
        }

        return super.saveOrUpdate(baseBusinessProgress);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            BaseBusinessProgress baseBusinessProgress = getById(id);
            if (baseBusinessProgress == null) {
                return false;
            } else if (baseBusinessProgress.getStatus() != null &&
                    (baseBusinessProgress.getStatus() != FormStatusConstant.STASH && baseBusinessProgress.getStatus() != FormStatusConstant.UNREVIEWED)) {
                return false;
            }
            formWorkflowService.deleteProcessInstance(String.valueOf(id));
        }

        boolean result = super.deleteLogic(ids);
        if (result) {
            businessProgressService.deleteByParentId(ids);
            taskProgressService.deleteByParentId(ids);
            majorProgressService.deleteByParentId(ids);
            mainProgressService.deleteByParentId(ids);
        }

        return result;
    }

    @Override
    public HashMap<String, Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW, null);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String, Object>();
    }

    @Override
    public Boolean finish(String id) {
        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH, "审批通过");
    }

    @Override
    public Boolean reject(String id, int formState, String comment) {
        return handleStatus(Long.valueOf(id), formState, comment);
    }

    @Override
    public String checkYear(BaseBusinessProgress baseBusinessProgress) {
        String fillingMonth = baseBusinessProgress.getFillingMonth();
        String fillingUnitId = baseBusinessProgress.getFillingUnitId();
        QueryWrapper<BaseBusinessProgress> queryWrapper = new QueryWrapper<>();
        if (!Optional.ofNullable(fillingMonth).isPresent()) {
            return "填报时间为空";
        }
        if (!Optional.ofNullable(fillingUnitId).isPresent()) {
            return "填报单位为空";
        }
        //判断该时间的基础表
        List<BaseBusinessIndicators> baseBusinessIndicators = baseBusinessIndicatorsService.list(new LambdaQueryWrapper<BaseBusinessIndicators>().eq(BaseBusinessIndicators::getStatus, 3)
                .eq(BaseBusinessIndicators::getFillingYear, fillingMonth.split("-")[0]).eq(BaseBusinessIndicators::getFillingUnitId, fillingUnitId)
                .eq(BaseBusinessIndicators::getModuleType, 0));
        if (CollectionUtil.isEmpty(baseBusinessIndicators)) {
            return "该年度基础表没填";
        }
        queryWrapper.eq("filling_unit_id", fillingUnitId);
        queryWrapper.eq("filling_month", fillingMonth);
        queryWrapper.eq("module_type", 0);
        BaseBusinessProgress one = getOne(queryWrapper);
        if (!Optional.ofNullable(one).isPresent()) {
            return null;
        }
        if (one.getId().equals(baseBusinessProgress.getId())) {
            return null;
        }
        return "该年度已填报";
    }

    /**
     * 统一处理状态机事件方法
     *
     * @param id           主键
     * @param updateStatus 更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus, String comment) {
        try {
            BaseBusinessProgress baseBusinessProgress = getById(id);
            /**
             * 设置审批人和审批时间
             */
            if (updateStatus == FormStatusConstant.FINISH) {
                baseBusinessProgress.setApprovedUser(TokenUtil.getTokenUserId());
                Date now = DateUtil.now();
                baseBusinessProgress.setApprovedTime(now);
            }
            if (StringUtil.isNotBlank(baseBusinessProgress.getDataSource()) &&
                    StringUtil.isNotBlank(baseBusinessProgress.getDataSourceId())) {
                if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT) {
                    ApprovalMessage approvalMessage = new ApprovalMessage();
                    approvalMessage.setDataSourceId(baseBusinessProgress.getDataSourceId());
                    approvalMessage.setOpinion(comment);
                    approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
                    approvalMessage.setIsSend(1);
                    approvalMessage.setDataSourceType(GZW_TYPE);

                    if (baseBusinessProgress.getDataSource().equals(YthConstant.DATA_NINGBO)) {
                        approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
                        approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
                        approvalMessage.setFormType(FormTypeConstant.PF_BUSINESS_REPLENISH);
                        approvalMessage.setFilingCode(baseBusinessProgress.getCode());
                    }
                    approvalMessageService.save(approvalMessage);
                }
            }
            baseBusinessProgress.setStatus(updateStatus);
            updateById(baseBusinessProgress);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<BaseBusinessProgress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseBusinessProgress::getModuleType, 0);
        queryWrapper.in(BaseBusinessProgress::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
        List<BaseBusinessProgress> baseBusinessProgresses = list(queryWrapper);
        List<BaseBusinessProgressVO> baseBusinessProgressVOS = baseBusinessProgressWrapper.entityToVO(baseBusinessProgresses);
        List<PageData> pageDataList = new ArrayList<>();
        try {
            if (CollectionUtil.isNotEmpty(baseBusinessProgressVOS)) {
                for (BaseBusinessProgressVO vo : baseBusinessProgressVOS) {
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getFillingUnitName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getFillingUnitId());
                    pd.put("formType", FormTypeConstant.PF_BUSINESS_REPLENISH);
                    pd.put("orgName", vo.getFillingUnitName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.PF_BUSINESS_REPLENISH);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean submit(BaseBusinessProgress baseBusinessProgress) {
        baseBusinessProgress.setModuleType(0);
        boolean result = saveOrUpdate(baseBusinessProgress);
        if (result) {
//            if (cn.hutool.core.collection.CollectionUtil.isNotEmpty(baseBusinessProgress.getDocList())) {
//                fileService.saveAll(baseBusinessProgress.getId().toString(), baseBusinessProgress.getDocList());
//            } else {
//                fileService.edit(baseBusinessProgress.getId().toString(), baseBusinessProgress.getDocList());
//            }
            List<BusinessProgress> baseIndicators = baseBusinessProgress.getBaseIndicators();
            List<BusinessProgress> categoryIndicators = baseBusinessProgress.getCategoryIndicators();
            List<BusinessProgress> industryIndicators = baseBusinessProgress.getIndustryIndicators();
            List<BusinessProgress> otherIndicators = baseBusinessProgress.getOtherIndicators();
            if (CollectionUtil.isNotEmpty(baseIndicators)){
                if(CollectionUtil.isNotEmpty(categoryIndicators)) baseIndicators.addAll(categoryIndicators);
                if(CollectionUtil.isNotEmpty(industryIndicators)) baseIndicators.addAll(industryIndicators);
                if(CollectionUtil.isNotEmpty(otherIndicators)) baseIndicators.addAll(otherIndicators);
                for (BusinessProgress progress : baseIndicators){
                    if (progress.getId() != null &&
                            Optional.ofNullable(progress.getIsDeleted()).isPresent() && progress.getIsDeleted().intValue() == 1) {
                        businessProgressService.removeById(progress.getId());
                    }else {
                        progress.setBaseBusinessProgressId(baseBusinessProgress.getId());
                        businessProgressService.saveOrUpdate(progress);
                    }
                }
            }

//            List<BusinessProgress> businessProgresses = baseBusinessProgress.getBusinessProgresses();
//            if (CollectionUtil.isNotEmpty(businessProgresses)) {
//                for (BusinessProgress businessProgress : businessProgresses) {
//                    if (businessProgress.getId() != null &&
//                            Optional.ofNullable(businessProgress.getIsDeleted()).isPresent() && businessProgress.getIsDeleted().intValue() == 1) {
//                        businessProgressService.removeById(businessProgress.getId());
//                    } else {
//                        businessProgress.setBaseBusinessProgressId(baseBusinessProgress.getId());
//                        businessProgressService.saveOrUpdate(businessProgress);
//                    }
//                }
//            }

//            List<TaskProgress> taskProgresses = baseBusinessProgress.getTaskProgresses();
//            if (CollectionUtil.isNotEmpty(taskProgresses)) {
//                for (TaskProgress taskProgress : taskProgresses) {
//                    //任务绩效表Id
//                    Long taskIndicatorsId = taskProgress.getTaskIndicatorsId();
//                    if (!Optional.ofNullable(taskIndicatorsId).isPresent()) {
//                        taskIndicatorsId = insertTaskIndicator(taskProgress, baseBusinessProgress);
//                        taskProgress.setTaskIndicatorsId(taskIndicatorsId);
//                    }
//                    if (taskProgress.getId() != null &&
//                            Optional.ofNullable(taskProgress.getIsDeleted()).isPresent() && taskProgress.getIsDeleted().intValue() == 1) {
//                        taskProgressService.removeById(taskProgress.getId());
//                    } else {
//                        taskProgress.setBaseBusinessProgressId(baseBusinessProgress.getId());
//                        taskProgressService.saveOrUpdate(taskProgress);
//                    }
//                }
//            }

            List<MajorProgress> majorProgresses = baseBusinessProgress.getMajorProgresses();
            if (CollectionUtil.isNotEmpty(majorProgresses)) {
                for (MajorProgress majorProgress : majorProgresses) {
                    //重大考核项目表Id
                    if (majorProgress.getId() != null &&
                            Optional.ofNullable(majorProgress.getIsDeleted()).isPresent() && majorProgress.getIsDeleted().intValue() == 1) {
                        majorProgressService.removeById(majorProgress.getId());
                    } else {
                        majorProgress.setBaseBusinessProgressId(baseBusinessProgress.getId());
                        majorProgressService.saveOrUpdate(majorProgress);
                    }
                }
            }

            List<MainProgress> mainProgresses = baseBusinessProgress.getMainProgresses();
            if (CollectionUtil.isNotEmpty(mainProgresses)) {
                for (MainProgress mainProgress : mainProgresses) {
                    //重大考核项目表Id
                    if (mainProgress.getId() != null &&
                            Optional.ofNullable(mainProgress.getIsDeleted()).isPresent() && mainProgress.getIsDeleted().intValue() == 1) {
                        mainProgressService.removeById(mainProgress.getId());
                    } else {
                        mainProgress.setBaseBusinessProgressId(baseBusinessProgress.getId());
                        mainProgressService.saveOrUpdate(mainProgress);
                    }
                }
            }
        }
        return result;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 任务绩效指标保存
     * @Date: 2:52 PM 2022/12/16
     * @Param: [taskProgress, baseBusinessProgress]
     * @return: java.lang.Long
     **/
    private Long insertTaskIndicator(TaskProgress taskProgress, BaseBusinessProgress baseBusinessProgress) {
        //先加基础表
        TaskIndicators taskIndicators = new TaskIndicators();
        taskIndicators.setBaseBusinessIndicatorsId(baseBusinessProgress.getBaseBusinessIndicatorsId());
        taskIndicators.setFillingMonth(baseBusinessProgress.getFillingMonth());
        taskIndicators.setIndexNum(taskProgress.getIndexNum());
        taskIndicators.setContent(taskProgress.getContent());
        taskIndicators.setIndicatorsCategoryId(taskProgress.getIndicatorsCategoryId());
        taskIndicatorsService.saveOrUpdate(taskIndicators);

        return taskIndicators.getId();
    }

    @Override
    public R<BaseBusinessProgressVO> getDetailObj(BaseBusinessProgressVO baseBusinessProgressVO) {
        if (!Optional.ofNullable(baseBusinessProgressVO).isPresent()) {
            return new R(CommonCode.FAIL);
        }
        List<BusinessProgressVO> businessProgressVOS = businessProgressWrapper
                .entityToVO(businessProgressService.list(new LambdaQueryWrapper<BusinessProgress>()
                        .eq(BusinessProgress::getBaseBusinessProgressId, baseBusinessProgressVO.getId())));
        if (CollectionUtil.isNotEmpty(businessProgressVOS)){
            businessProgressService.setDetailList(businessProgressVOS);
        }
        baseBusinessProgressVO.setBusinessProgressVOS(businessProgressVOS);

        // 查询指标分类
        List<AppraisalIndex> appIndexList = appraisalIndexService.list(new LambdaQueryWrapper<AppraisalIndex>()
                .eq(AppraisalIndex::getTableCode, "001").eq(AppraisalIndex::getType,1));
        Map<Long, List<BusinessProgressVO>> map = businessProgressVOS.stream().collect(Collectors.groupingBy(BusinessProgressVO::getIndicatorsCategoryId, Collectors.toList()));
        if(CollectionUtil.isNotEmpty(appIndexList)){
            appIndexList.forEach(a ->{
                if(map.containsKey(a.getId()) && StringUtils.isNotBlank(a.getName())){
                    List<BusinessProgressVO> list = map.get(a.getId());
//					list.forEach(b -> b.setIndicatorsCategoryName(a.getName()));
                    if("基本指标".equals(a.getName())){
                        baseBusinessProgressVO.setBaseIndicatorsVOS(list);
                    } else if ("分类指标".equals(a.getName())) {
                        baseBusinessProgressVO.setCategoryIndicatorsVOS(list);
                    } else if("行业指标".equals(a.getName())) {
                        baseBusinessProgressVO.setIndustryIndicatorsVOS(list);
                    } else if("其他".equals(a.getName())) {
                        baseBusinessProgressVO.setOtherIndicatorsVOS(list);
                    }
                }
            });
        }

//        List<TaskProgressVO> taskProgressVOS = taskProgressWrapper
//                .entityToVO(taskProgressService.list(new LambdaQueryWrapper<TaskProgress>()
//                        .eq(TaskProgress::getBaseBusinessProgressId, baseBusinessProgressVO.getId())));
//        if (CollectionUtil.isNotEmpty(taskProgressVOS)) {
//            taskProgressService.setDetailList(taskProgressVOS);
//        }
//        baseBusinessProgressVO.setTaskProgressVOS(taskProgressVOS);

        List<MajorProgressVO> majorProgressVOS = majorProgressWrapper
                .entityToVO(majorProgressService.list(new LambdaQueryWrapper<MajorProgress>()
                        .eq(MajorProgress::getBaseBusinessProgressId, baseBusinessProgressVO.getId())));
        if (CollectionUtil.isNotEmpty(majorProgressVOS)) {
            majorProgressService.setDetailList(majorProgressVOS);
        }
        baseBusinessProgressVO.setMajorProgressVOS(majorProgressVOS);

        List<MainProgressVO> mainProgressVOS = mainProgressWrapper
                .entityToVO(mainProgressService.list(new LambdaQueryWrapper<MainProgress>()
                        .eq(MainProgress::getBaseBusinessProgressId, baseBusinessProgressVO.getId())));
        if (CollectionUtil.isNotEmpty(mainProgressVOS)) {
            mainProgressService.setDetailList(mainProgressVOS);
        }
        baseBusinessProgressVO.setMainProgressVOS(mainProgressVOS);

        //履职成效
        BaseBusinessIndicators indicators = baseBusinessIndicatorsService.getById(baseBusinessProgressVO.getBaseBusinessIndicatorsId());
        if (indicators != null) {
            baseBusinessProgressVO.setTargetValue(indicators.getTargetValue());
            baseBusinessProgressVO.setRemarks(indicators.getRemarks());
            baseBusinessProgressVO.setIsMajorProject(indicators.getIsMajorProject());
        }

        R<BaseBusinessProgressVO> objResult = new R<>(CommonCode.SUCCESS);
        objResult.setPageData(baseBusinessProgressVO);
        return objResult;
    }

    @Override
    public void goBackToStash(String formId) {
        handleStatus(Long.valueOf(formId), UNREVIEWED, null);
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 根据年度和填报时间获取基础表
     * @Date: 10:56 AM 2022/12/16
     * @Param: [dto]
     * @return: com.plian.system.vo.pf.BaseBusinessProgressVO
     **/
    @Override
    public BaseBusinessProgressVO getDetailByDto(BaseBusinessProgressDTO dto) {
        BaseBusinessProgressVO progressVO = new BaseBusinessProgressVO();
        BaseBusinessIndicatorsVO indicatorsVO = baseBusinessIndicatorsService.getDetailByMonth(dto.getFillingMonth(), dto.getFillingUnitId());
        //获取上个月 - 任务绩效
        String fillingMonth = dto.getFillingMonth();
        progressVO.setFillingMonth(fillingMonth);
        progressVO.setFillingUnitId(dto.getFillingUnitId());
        if (!"01".equals(fillingMonth.split("-")[1])) {
            Date old = DateUtil.minusMonths(DateUtil.parse(fillingMonth, DateUtil.PATTERN_MONTH), 1);
            String oldMonth = DateUtil.format(old, DateUtil.PATTERN_MONTH);
            BaseBusinessProgress oldProgress = getOne(new LambdaQueryWrapper<BaseBusinessProgress>().eq(BaseBusinessProgress::getFillingUnitId, dto.getFillingUnitId())
                    .eq(BaseBusinessProgress::getModuleType, 0).eq(BaseBusinessProgress::getFillingMonth, oldMonth));
            if (Optional.ofNullable(oldProgress).isPresent()) {
                BaseBusinessProgressVO oldProgressVO = baseBusinessProgressWrapper.entityToVO(oldProgress);
                getDetailObj(oldProgressVO);
                //任务绩效
                List<TaskProgressVO> taskProgressVOS = oldProgressVO.getTaskProgressVOS();
                progressVO.setTaskProgressVOS(taskProgressVOS);
                //主责主页
                List<MainProgressVO> mainProgressVOS = oldProgressVO.getMainProgressVOS();
                progressVO.setMainProgressVOS(mainProgressVOS);
            } else {
                setTaskProgress(progressVO, indicatorsVO.getTaskIndicatorsVOS());

                setMainProgress(progressVO, indicatorsVO.getMainBusinesses());
            }
        } else {
            if (Optional.ofNullable(indicatorsVO).isPresent()) {
                //任务绩效
                setTaskProgress(progressVO, indicatorsVO.getTaskIndicatorsVOS());
                //主责主业
                setMainProgress(progressVO, indicatorsVO.getMainBusinesses());
            }
        }
        if (Optional.ofNullable(indicatorsVO).isPresent()) {
            //主表Id
            progressVO.setBaseBusinessIndicatorsId(indicatorsVO.getId());
            //财务绩效
            setBusinessProgress(progressVO, indicatorsVO.getBusinessIndicatorsVOS());

            //履职成效
            progressVO.setTargetValue(indicatorsVO.getTargetValue());
            progressVO.setRemarks(indicatorsVO.getRemarks());
            progressVO.setIsMajorProject(indicatorsVO.getIsMajorProject());
            //重大工程
            setMajorProgress(progressVO, indicatorsVO.getMajorProjects());
        }

        if (CollectionUtil.isNotEmpty(progressVO.getBusinessProgressVOS())) {
            // 查询指标分类
            List<AppraisalIndex> appIndexList = appraisalIndexService.list(new LambdaQueryWrapper<AppraisalIndex>()
                    .eq(AppraisalIndex::getTableCode, "001").eq(AppraisalIndex::getType,1));
            Map<Long, List<BusinessProgressVO>> map = progressVO.getBusinessProgressVOS().stream().collect(Collectors.groupingBy(BusinessProgressVO::getIndicatorsCategoryId, Collectors.toList()));
            if(CollectionUtil.isNotEmpty(appIndexList)){
                appIndexList.forEach(a ->{
                    if(map.containsKey(a.getId()) && StringUtils.isNotBlank(a.getName())){
                        List<BusinessProgressVO> list = map.get(a.getId());
    //					list.forEach(b -> b.setIndicatorsCategoryName(a.getName()));
                        if("基本指标".equals(a.getName())){
                            progressVO.setBaseIndicatorsVOS(list);
                        } else if ("分类指标".equals(a.getName())) {
                            progressVO.setCategoryIndicatorsVOS(list);
                        } else if("行业指标".equals(a.getName())) {
                            progressVO.setIndustryIndicatorsVOS(list);
                        } else if("其他".equals(a.getName())) {
                            progressVO.setOtherIndicatorsVOS(list);
                        }
                    }
                });
            }
        }

        return progressVO;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 根据年份获取最新的任务绩效/重大工程/主责主业/财务绩效
     * @Date: 8:58 PM 2022/12/19
     * @Param: [fillingYear, fillingUnitId]
     * @return: java.util.List<com.plian.system.vo.pf.TaskProgressVO>
     **/
    @Override
    public BaseBusinessProgressVO getBasicTaskProgress(String fillingYear, String fillingUnitId) {
        BaseBusinessProgressVO progressVO = new BaseBusinessProgressVO();
        List<TaskProgressVO> taskProgressVOS = new ArrayList<>();
        List<MajorProgressVO> majorProgressVOS = new ArrayList<>();
        List<MainProgressVO> mainProgressVOS = new ArrayList<>();
        List<BusinessProgressVO> businessProgressVOS = new ArrayList<>();

        List<BaseBusinessProgress> baseBusinessProgresses = list(new LambdaQueryWrapper<BaseBusinessProgress>().likeRight(BaseBusinessProgress::getFillingMonth, fillingYear).eq(BaseBusinessProgress::getFillingUnitId, fillingUnitId).eq(BaseBusinessProgress::getStatus, 3)
                .eq(BaseBusinessProgress::getModuleType, 0));
        if (CollectionUtil.isNotEmpty(baseBusinessProgresses)) {
            //最新一条
            BaseBusinessProgress baseBusinessProgress = baseBusinessProgresses.stream().sorted(Comparator.comparing(BaseBusinessProgress::getFillingMonth).reversed()).collect(Collectors.toList()).get(0);
            //有效完成率
            progressVO.setEffectiveRate(baseBusinessProgress.getEffectiveRate());
            //财务绩效
            List<BusinessProgress> businessProgresses = businessProgressService.list(new LambdaQueryWrapper<BusinessProgress>().eq(BusinessProgress::getBaseBusinessProgressId, baseBusinessProgress.getId()));
            businessProgressVOS = businessProgressWrapper.entityToVO(businessProgresses);
            businessProgressService.setDetailList(businessProgressVOS);

            //任务绩效
            List<TaskProgress> taskProgresses = taskProgressService.list(new LambdaQueryWrapper<TaskProgress>().eq(TaskProgress::getBaseBusinessProgressId, baseBusinessProgress.getId()));
            taskProgressVOS = taskProgressWrapper.entityToVO(taskProgresses);
            taskProgressService.setDetailList(taskProgressVOS);
            //重大工程
            List<MajorProgress> majorProgresses = majorProgressService.list(new LambdaQueryWrapper<MajorProgress>().eq(MajorProgress::getBaseBusinessProgressId, baseBusinessProgress.getId()));
            majorProgressVOS = majorProgressWrapper.entityToVO(majorProgresses);
            majorProgressService.setDetailList(majorProgressVOS);
            //主责主业
            List<MainProgress> mainProgresses = mainProgressService.list(new LambdaQueryWrapper<MainProgress>().eq(MainProgress::getBaseBusinessProgressId, baseBusinessProgress.getId()));
            mainProgressVOS = mainProgressWrapper.entityToVO(mainProgresses);
            mainProgressService.setDetailList(mainProgressVOS);
        } else {
            //todo 没有月度的重大工程 去取 申报
            List<BaseBusinessIndicators> baseBusinessIndicators = baseIndicatorsMapper.selectList(Wrappers.<BaseBusinessIndicators>lambdaQuery().eq(BaseBusinessIndicators::getFillingUnitId, fillingUnitId).eq(BaseBusinessIndicators::getFillingYear, fillingYear)
                    .eq(BaseBusinessIndicators::getModuleType, 0));
            if (CollectionUtil.isNotEmpty(baseBusinessIndicators)) {
                //最新一条
                BaseBusinessIndicators baseBusinessIndicator = baseBusinessIndicators.stream().sorted(Comparator.comparing(BaseBusinessIndicators::getCreateTime).reversed()).collect(Collectors.toList()).get(0);
                List<MajorProject> majorProjects = majorProjectMapper.selectList(Wrappers.<MajorProject>lambdaQuery().eq(MajorProject::getBaseBusinessIndicatorsId, baseBusinessIndicator.getId()));
                progressVO.setFillingMonth(fillingYear + "-12");
                progressVO.setFillingUnitId(fillingUnitId);
                setMajorProgress(progressVO, majorProjects);
                majorProgressVOS = progressVO.getMajorProgressVOS();
            }
        }
        progressVO.setBusinessProgressVOS(businessProgressVOS);
        progressVO.setTaskProgressVOS(taskProgressVOS);
        progressVO.setMainProgressVOS(mainProgressVOS);
        progressVO.setMajorProgressVOS(majorProgressVOS);
        return progressVO;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 放财务绩效
     * @Date: 10:49 AM 2022/12/16
     * @Param: [progressVO, businessIndicatorsVOS]
     * @return: void
     **/
    private void setBusinessProgress(BaseBusinessProgressVO progressVO, List<BusinessIndicatorsVO> businessIndicatorsVOS) {
        if (CollectionUtil.isNotEmpty(businessIndicatorsVOS)) {
            //基础表 - id/计算
            List<IndicatorsValue> values = getValues(progressVO.getFillingMonth(), progressVO.getFillingUnitId());
            //指标
            List<AppraisalIndex> appraisalIndices = appraisalIndexService.listByTableCodeAndYear("001", progressVO.getFillingMonth().split("-")[0]);

            List<FinanceIndicators> indicators = indicatorsMapper.selectList(null);

            //VO 表/展示
            List<BusinessProgressVO> businessProgressVOS = new ArrayList<>();
            for (BusinessIndicatorsVO vo : businessIndicatorsVOS) {
                //vo
                BusinessProgressVO businessProgressVO = new BusinessProgressVO();
                businessProgressVO.setBusinessIndicatorsId(vo.getId());
                businessProgressVO.setIndicatorsCategoryName(vo.getIndicatorsCategoryName());
                businessProgressVO.setIndicatorsWeight(vo.getIndicatorsWeight());
                businessProgressVO.setBaseline(vo.getBaseline());
                businessProgressVO.setTarget(vo.getTarget());
                businessProgressVO.setBasicTarget(vo.getBasicTarget());
                businessProgressVO.setIndicatorsCategoryId(vo.getIndicatorsCategoryId());

                if (Optional.ofNullable(vo.getIndicatorsCategoryId()).isPresent()) {
                    //计算
                    BigDecimal bigDecimal = switchByCode(vo, values, indicators, appraisalIndices, progressVO.getFillingMonth(), progressVO.getFillingUnitId());
                    businessProgressVO.setPerformCalculate(bigDecimal);
                }
                businessProgressVOS.add(businessProgressVO);
            }
            progressVO.setBusinessProgressVOS(businessProgressVOS);
        }
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 得到指标值
     * @Date: 3:18 PM 2022/12/22
     * @Param: [fillingMonth, fillingUnitId]
     * @return: java.util.List<com.plian.system.entity.fr.indicators.IndicatorsValue>
     **/
    private List<IndicatorsValue> getValues(String fillingMonth, String fillingUnitId) {
        String year = fillingMonth.split("-")[0];
        String month = fillingMonth.split("-")[1];
        return indicatorsValueMapper.selectList(new LambdaQueryWrapper<IndicatorsValue>().eq(IndicatorsValue::getFyear, year).eq(IndicatorsValue::getFmonth, month).eq(IndicatorsValue::getOrgId, fillingUnitId).eq(IndicatorsValue::getIsGroup, 1));
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 获取Value
     * @Date: 2:43 PM 2022/12/27
     * @Param: [indicatorsVO, values, appraisalIndices, fillingMonth, fillingUnitId]
     * @return: java.math.BigDecimal
     **/
    private BigDecimal switchByCode(BusinessIndicatorsVO indicatorsVO, List<IndicatorsValue> values, List<FinanceIndicators> indicators,
                                    List<AppraisalIndex> appraisalIndices, String fillingMonth, String fillingUnitId) {
        BigDecimal result = BigDecimal.ZERO;
        //code
        List<AppraisalIndex> indexList = appraisalIndices.stream().filter(m -> m.getId().equals(indicatorsVO.getIndicatorsCategoryId())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(indexList)) {
            AppraisalIndex appraisalIndex = indexList.get(0);
            if (appraisalIndex.getFlag() == 0) {
                String completeCode = appraisalIndex.getCompleteCode();
                switch (completeCode) {
                    case "KH1":
                        result = getEquityReturn(values, fillingMonth, indicators);
                        break;
                    case "KH2":
                        result = getCapitaNet(values, indicators);
                        break;
                    case "KH3":
                        result = getRevenue(values, fillingMonth, fillingUnitId, indicators);
                        break;
                    case "KH4":
                        result = getFinancingCostRate(fillingMonth, fillingUnitId);
                        break;
                    case "KH5":
                        result = getPercentageRevenue(values, indicators);
                        break;
                    default:
                        return null;
                }
            } else {
                return null;
            }
        }
        return result;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO  净资产收益率 : KLJ21/（（K37+KLAST37）/2）*（当月月份数/12)*100%
     * @Date: 2:49 PM 2022/12/22
     * @Param: [indicatorsValues, fillingMonth, fillingUnitId]
     * @return: java.math.BigDecimal
     **/
    private BigDecimal getEquityReturn(List<IndicatorsValue> indicatorsValues, String fillingMonth, List<FinanceIndicators> indicators) {
        //月份数
        BigDecimal month = new BigDecimal(fillingMonth.split("-")[1]);

        BigDecimal equityReturn = BigDecimal.ZERO;
        //KLJ21
        String KLJ21ID = indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.KLJ21)).collect(Collectors.toList()).get(0).getId();
        List<IndicatorsValue> KLJ21Values = indicatorsValues.stream().filter(value -> KLJ21ID.equals(value.getIndicatorsId())).collect(Collectors.toList());

        //K37
        String K37ID = indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.K37)).collect(Collectors.toList()).get(0).getId();
        List<IndicatorsValue> K37Values = indicatorsValues.stream().filter(value -> K37ID.equals(value.getIndicatorsId())).collect(Collectors.toList());

        //KLAST37
        String KLAST37ID = indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.KLAST37)).collect(Collectors.toList()).get(0).getId();
        List<IndicatorsValue> KLAST37Values = indicatorsValues.stream().filter(value -> KLAST37ID.equals(value.getIndicatorsId())).collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(KLJ21Values) &&
                (CollectionUtil.isNotEmpty(K37Values) || CollectionUtil.isNotEmpty(KLAST37Values))) {
            BigDecimal value = (K37Values.get(0).getFvalue().add(KLAST37Values.get(0).getFvalue())).divide(new BigDecimal(2), 4, RoundingMode.HALF_UP);
            BigDecimal monthDivide = new BigDecimal(12).divide(month, 4, RoundingMode.HALF_UP);
            if (value.compareTo(BigDecimal.ZERO) > 0) {
                equityReturn = (KLJ21Values.get(0).getFvalue().multiply(new BigDecimal(100))).divide(value, 4, RoundingMode.HALF_UP).multiply(monthDivide);
            }
        }
        return equityReturn;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 人均归母净利润 : KLJ21/K45
     * @Date: 2:56 PM 2022/12/22
     * @Param: [indicatorsValues]
     * @return: java.math.BigDecimal
     **/
    private BigDecimal getCapitaNet(List<IndicatorsValue> indicatorsValues, List<FinanceIndicators> indicators) {
        BigDecimal capitaNet = BigDecimal.ZERO;
        //KLJ21
        String KLJ21ID = indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.KLJ21)).collect(Collectors.toList()).get(0).getId();
        List<IndicatorsValue> KLJ21Values = indicatorsValues.stream().filter(value -> KLJ21ID.equals(value.getIndicatorsId())).collect(Collectors.toList());

        //K45
        String K45ID = indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.K45)).collect(Collectors.toList()).get(0).getId();
        List<IndicatorsValue> K45Values = indicatorsValues.stream().filter(value -> K45ID.equals(value.getIndicatorsId())).collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(KLJ21Values) && CollectionUtil.isNotEmpty(K45Values)) {
            BigDecimal KLJ21Value = KLJ21Values.get(0).getFvalue();
            BigDecimal K45Value = K45Values.get(0).getFvalue();
            if (Optional.ofNullable(KLJ21Value).isPresent() && Optional.ofNullable(K45Value).isPresent() && K45Value.compareTo(BigDecimal.ZERO) > 0) {
                capitaNet = KLJ21Value.divide(K45Value, 4, RoundingMode.HALF_UP);
            }
        }
        return capitaNet;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 营业收入完成率 : (KLJ1/ (去年12月的KLJ1 * 110%)) )  * 100%
     * @Date: 3:00 PM 2022/12/22
     * @Param: [indicatorsValues]
     * @return: java.math.BigDecimal
     **/
    private BigDecimal getRevenue(List<IndicatorsValue> indicatorsValues, String fillingMonth, String fillingUnitId, List<FinanceIndicators> indicators) {
        BigDecimal revenue = BigDecimal.ZERO;
        //KLJ1
        String KLJ1ID = indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.KLJ1)).collect(Collectors.toList()).get(0).getId();
        List<IndicatorsValue> KLJ1Values = indicatorsValues.stream().filter(value -> KLJ1ID.equals(value.getIndicatorsId())).collect(Collectors.toList());

        //去年12月的KLJ1
        String year = fillingMonth.split("-")[0];
        String KLASTLJ1ID = indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.KLASTLJ1)).collect(Collectors.toList()).get(0).getId();
        List<IndicatorsValue> KLASTLJ1Values = indicatorsValueMapper.selectList(new LambdaQueryWrapper<IndicatorsValue>().eq(IndicatorsValue::getFyear, year).eq(IndicatorsValue::getFmonth, 12).eq(IndicatorsValue::getOrgId, fillingUnitId)
                .eq(IndicatorsValue::getIndicatorsId, KLASTLJ1ID).eq(IndicatorsValue::getIsGroup, 1));

        if (CollectionUtil.isNotEmpty(KLJ1Values) && CollectionUtil.isNotEmpty(KLASTLJ1Values)) {
            BigDecimal KLJ1Value = KLJ1Values.get(0).getFvalue();
            BigDecimal KLASTLJ1Value = KLASTLJ1Values.get(0).getFvalue();
            if (Optional.ofNullable(KLJ1Value).isPresent() && Optional.ofNullable(KLASTLJ1Value).isPresent()
                    && (KLASTLJ1Value.compareTo(BigDecimal.ZERO) > 0)) {
                KLASTLJ1Value = KLASTLJ1Value.multiply(new BigDecimal(110)).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP);
                revenue = KLJ1Value.multiply(new BigDecimal(100)).divide(KLASTLJ1Value, 4, RoundingMode.HALF_UP);
            }
        }
        return revenue;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 成本费用占营业收入:(K2SUM + K3SUM + K4SUM +K5SUM + K6SUM +  K7SUM ) / KLJ1 * 100%
     * @Date: 3:14 PM 2022/12/22
     * @Param: [indicatorsValues]
     * @return: java.math.BigDecimal
     **/
    private BigDecimal getPercentageRevenue(List<IndicatorsValue> indicatorsValues, List<FinanceIndicators> indicators) {
        BigDecimal percentageRevenue = BigDecimal.ZERO;
        //成本费用
        BigDecimal cost = addCost(indicatorsValues, indicators);
        //KLJ1
        String KLJ1ID = indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.KLJ1)).collect(Collectors.toList()).get(0).getId();
        List<IndicatorsValue> KLJ1Values = indicatorsValues.stream().filter(value -> KLJ1ID.equals(value.getIndicatorsId())).collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(KLJ1Values)) {
            BigDecimal fvalue = KLJ1Values.get(0).getFvalue();
            if (Optional.ofNullable(fvalue).isPresent() && fvalue.compareTo(BigDecimal.ZERO) != 0) {
                percentageRevenue = cost.multiply(new BigDecimal(100)).divide(fvalue, 4, RoundingMode.HALF_UP);
            }
        }
        return percentageRevenue;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 成本费用 K2SUM + K3SUM + K4SUM +K5SUM + K6SUM + K7SUM
     * @Date: 3:08 PM 2022/12/22
     * @Param: [indicatorsValues]
     * @return: java.math.BigDecimal
     **/
    private BigDecimal addCost(List<IndicatorsValue> indicatorsValues, List<FinanceIndicators> indicators) {
        BigDecimal cost = BigDecimal.ZERO;
        List<IndicatorsValue> K2SUMValues = indicatorsValues.stream()
                .filter(value ->
                        indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.K2SUM)).collect(Collectors.toList()).get(0).getId()
                                .equals(value.getIndicatorsId()))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(K2SUMValues)) {
            cost = cost.add(K2SUMValues.get(0).getFvalue());
        }

        List<IndicatorsValue> K3SUMValues = indicatorsValues.stream()
                .filter(value ->
                        indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.K3SUM)).collect(Collectors.toList()).get(0).getId()
                                .equals(value.getIndicatorsId()))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(K3SUMValues)) {
            cost = cost.add(K3SUMValues.get(0).getFvalue());
        }

        List<IndicatorsValue> K4SUMValues = indicatorsValues.stream()
                .filter(value ->
                        indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.K4SUM)).collect(Collectors.toList()).get(0).getId()
                                .equals(value.getIndicatorsId()))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(K4SUMValues)) {
            cost = cost.add(K4SUMValues.get(0).getFvalue());
        }

        List<IndicatorsValue> K5SUMValues = indicatorsValues.stream()
                .filter(value ->
                        indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.K5SUM)).collect(Collectors.toList()).get(0).getId()
                                .equals(value.getIndicatorsId()))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(K5SUMValues)) {
            cost = cost.add(K5SUMValues.get(0).getFvalue());
        }

        List<IndicatorsValue> K6SUMValues = indicatorsValues.stream()
                .filter(value ->
                        indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.K6SUM)).collect(Collectors.toList()).get(0).getId()
                                .equals(value.getIndicatorsId()))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(K6SUMValues)) {
            cost = cost.add(K6SUMValues.get(0).getFvalue());
        }

        List<IndicatorsValue> K7SUMValues = indicatorsValues.stream()
                .filter(value ->
                        indicators.stream().filter(m -> m.getCode().equals(IndicatorsCodeConstant.K7SUM)).collect(Collectors.toList()).get(0).getId()
                                .equals(value.getIndicatorsId()))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(K7SUMValues)) {
            cost = cost.add(K7SUMValues.get(0).getFvalue());
        }

        return cost;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 融资成本率
     * @Date: 2:42 PM 2022/12/27
     * @Param: [fillingMonth, fillingUnitId]
     * @return: java.math.BigDecimal
     **/
    private BigDecimal getFinancingCostRate(String fillingMonth, String fillingUnitId) {
        BigDecimal cost = BigDecimal.ZERO;
        List<BankOrgStorage> list = bankOrgStorageService.list(new LambdaQueryWrapper<BankOrgStorage>().eq(BankOrgStorage::getOrgId, fillingUnitId).like(BankOrgStorage::getDate, fillingMonth));
        if (CollectionUtil.isNotEmpty(list)) {
            cost = list.stream().sorted(Comparator.comparing(BankOrgStorage::getDate).reversed()).collect(Collectors.toList()).get(0).getFinancingCostRate();
        }

        return cost;
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 放任务绩效
     * @Date: 10:54 AM 2022/12/16
     * @Param: [progressVO, taskIndicatorsVOS]
     * @return: void
     **/
    private void setTaskProgress(BaseBusinessProgressVO progressVO, List<TaskIndicatorsVO> taskIndicatorsVOS) {
        if (CollectionUtil.isNotEmpty(taskIndicatorsVOS)) {
            //VO 表/展示
            List<TaskProgressVO> taskProgressVOS = new ArrayList<>();
            for (TaskIndicatorsVO vo : taskIndicatorsVOS) {
                TaskProgress taskProgress = new TaskProgress();
                taskProgress.setTaskIndicatorsId(vo.getId());

//				taskProgresses.add(taskProgress);

                //vo
                TaskProgressVO taskProgressVO = new TaskProgressVO();
                taskProgressVO.setTaskIndicatorsId(vo.getId());

                taskProgressVO.setIndicatorsCategoryName(vo.getIndicatorsCategoryName());
                taskProgressVO.setIndicatorsCategoryId(vo.getIndicatorsCategoryId());
                taskProgressVO.setIndexNum(vo.getIndexNum());
                taskProgressVO.setContent(vo.getContent());
                taskProgressVO.setFillingMonth(vo.getFillingMonth());

                taskProgressVOS.add(taskProgressVO);
            }
//			progressVO.setTaskProgresses(taskProgresses);
            progressVO.setTaskProgressVOS(taskProgressVOS);
        }
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 放重大考核项目
     * @Date: 5:28 PM 2023/1/3
     * @Param: [progressVO, majorProjects]
     * @return: void
     **/
    private void setMajorProgress(BaseBusinessProgressVO progressVO, List<MajorProject> majorProjects) {
        if (CollectionUtil.isNotEmpty(majorProjects)) {
            //VO 表/展示
            List<MajorProgressVO> majorProgressVOS = new ArrayList<>();
            for (MajorProject vo : majorProjects) {
                //vo
                MajorProgressVO majorProgressVO = new MajorProgressVO();
                majorProgressVO.setMajorProjectId(vo.getId());
                majorProgressVO.setIndexNum(vo.getIndexNum());
                majorProgressVO.setProjectId(vo.getProjectId());
                majorProgressVO.setProjectName(vo.getProjectName());
                majorProgressVOS.add(majorProgressVO);
            }
            //todo 计算
            BaseInvestmentExecution execution = baseInvestmentExecutionService.getOne(new LambdaQueryWrapper<BaseInvestmentExecution>().eq(BaseInvestmentExecution::getFilingUnitId, progressVO.getFillingUnitId()).eq(BaseInvestmentExecution::getFilingMonth, progressVO.getFillingMonth()));
            if (Optional.ofNullable(execution).isPresent()) {
                EffectiveInvestment effectiveInvestment = effectiveInvestmentService.getOne(new LambdaQueryWrapper<EffectiveInvestment>().eq(EffectiveInvestment::getBaseInvestmentExecutionId, execution.getId()));
                if (Optional.ofNullable(effectiveInvestment).isPresent()) {
                    //有效完成率
                    BigDecimal planEffectiveInvestment = effectiveInvestment.getPlanEffectiveInvestment();
                    BigDecimal allCompleteInvestment = effectiveInvestment.getAllCompleteInvestment();
                    if (allCompleteInvestment.compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal effectiveRate = planEffectiveInvestment.multiply(new BigDecimal(100)).divide(allCompleteInvestment, 2, RoundingMode.HALF_UP);
                        progressVO.setEffectiveRate(effectiveRate);
                    }

                    List<ExecutionProjectSituation> projectSituations = executionProjectSituationService.list(new LambdaQueryWrapper<ExecutionProjectSituation>().eq(ExecutionProjectSituation::getEffectiveInvestmentId, effectiveInvestment.getId()));
                    if (CollectionUtil.isNotEmpty(projectSituations)) {
                        majorProgressVOS.forEach(majorProgressVO -> {
                            List<ExecutionProjectSituation> situations = projectSituations.stream().filter(m -> Optional.ofNullable(m.getProjectId()).isPresent() && Optional.ofNullable(majorProgressVO.getProjectId()).isPresent() && majorProgressVO.getProjectId().equals(m.getProjectId())).collect(Collectors.toList());
                            if (CollectionUtil.isNotEmpty(situations)) {
                                ExecutionProjectSituation situation = situations.get(0);
                                majorProgressVO.setCompleteMonth(situation.getCompleteInvestment());
                                //todo 本年度累计完成率
                                majorProgressVO.setImageProgress(situation.getMainProgress());
                            }
                        });
                    }
                }
            }
            progressVO.setMajorProgressVOS(majorProgressVOS);
        }
    }

    /**
     * @Author: Take-off
     * @Description: //TODO 放主责主业
     * @Date: 5:31 PM 2023/1/3
     * @Param: [progressVO, mainBusinesses]
     * @return: void
     **/
    private void setMainProgress(BaseBusinessProgressVO progressVO, List<MainBusiness> mainBusinesses) {
        if (CollectionUtil.isNotEmpty(mainBusinesses)) {
            //VO 表/展示
            List<MainProgressVO> mainProgressVOS = new ArrayList<>();
            for (MainBusiness vo : mainBusinesses) {
                //vo
                MainProgressVO majorProgressVO = new MainProgressVO();
                majorProgressVO.setMainBusinessId(vo.getId());
                majorProgressVO.setIndexNum(vo.getIndexNum());
                majorProgressVO.setEvaluation(vo.getEvaluation());
                mainProgressVOS.add(majorProgressVO);
            }
            progressVO.setMainProgressVOS(mainProgressVOS);
        }
    }

    @Override
    public String saveBaseBusiness(String data) {
        YthResult ythResult = new YthResult();
        List<String> successIds = new ArrayList<>();
        List<String> failIds = new ArrayList<>();
        List<String> failReasons = new ArrayList<>();

        List<BaseBusinessProgress> dataList = JSON.parseArray(data, BaseBusinessProgress.class);
        if (CollectionUtil.isNotEmpty(dataList)) {
            Map<String, String> orgSourceMap = orgService.getSourceId();
            List<BaseBusinessIndicators> indicators = baseBusinessIndicatorsService.getSourceData();
            //根据datasourceIds 查询出所有的数据
            List<BaseBusinessProgress> list = list(new LambdaQueryWrapper<BaseBusinessProgress>().in(BaseBusinessProgress::getDataSourceId, dataList.stream().map(BaseBusinessProgress::getDataSourceId).toArray()).eq(BaseBusinessProgress::getStatus, UNREVIEWED)
                    .eq(BaseBusinessProgress::getModuleType, 0));
            if (CollectionUtil.isNotEmpty(list)) {
                //删除子集
                List<Long> ids = list.stream().map(BaseBusinessProgress::getId).collect(Collectors.toList());
                businessProgressService.deleteByParentId(ids);
                taskProgressService.deleteByParentId(ids);
                majorProgressService.deleteByParentId(ids);
                mainProgressService.deleteByParentId(ids);
            }
            for (BaseBusinessProgress entity : dataList) {
                transfer(entity, orgSourceMap, indicators);
                //id重复略过
                if (CollectionUtil.isNotEmpty(list)) {
                    List<String> olIds = list.stream().map(BaseBusinessProgress::getDataSourceId).collect(Collectors.toList());
                    String dataSourceId = entity.getDataSourceId();
                    //判断数据库中是否有数据
                    if (olIds.contains(dataSourceId)) {
                        for (BaseBusinessProgress oldEntity : list) {
                            if (dataSourceId.equals(oldEntity.getDataSourceId())) {
                                //判断status是否为0，如果是0，就更新，不是0，就不更新
                                if (CheckStatus.checkCode(oldEntity.getStatus())) {
                                    successIds.add(dataSourceId);
                                    entity.setId(oldEntity.getId());
                                    entity.setDataSource(YthConstant.DATA_NINGBO);
                                    submit(entity);
                                    list.remove(oldEntity);
                                    break;
                                } else {
                                    failIds.add(dataSourceId);
                                    failReasons.add("dataSourceId:" + dataSourceId + "数据已提交且已经在流程中，无法更新");
                                    break;
                                }
                            }
                        }
                    } else {
                        //如果数据库中没有数据，就新增
                        entity.setDataSource(YthConstant.DATA_NINGBO);
                        submit(entity);
                        successIds.add(entity.getDataSourceId());
                    }
                } else {
                    //如果数据库中没有数据，就新增
                    entity.setDataSource(YthConstant.DATA_NINGBO);
                    submit(entity);
                    successIds.add(entity.getDataSourceId());
                }
            }
        } else {
            failReasons.add("数据为空");
        }
        ythResult.setSuccessIds(successIds);
        ythResult.setFailIds(failIds);
        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
        //ythResult转换成json字符串
        return JSON.toJSONString(ythResult);
    }

    private void transfer(BaseBusinessProgress entity, Map<String, String> orgSourceMap, List<BaseBusinessIndicators> indicators) {
        Optional.ofNullable(entity.getFillingUnitId()).ifPresent(m ->
                {
                    String orgId = orgSourceMap.get(m);
                    if (StringUtil.isNotBlank(orgId)) {
                        entity.setFillingUnitId(orgId);
                        entity.setCreateCompanyId(orgId);
                    }
                }
        );
        //转换code
        String baseIndicatorsCodeId = entity.getBaseIndicatorsCodeId();
        if (Optional.ofNullable(baseIndicatorsCodeId).isPresent()) {
            Optional<BaseBusinessIndicators> indicatorsOptional = indicators.stream().filter(m -> baseIndicatorsCodeId.equals(m.getDataSourceId())).findFirst();
            if (indicatorsOptional.isPresent()) {
                BaseBusinessIndicators baseIndicator = indicatorsOptional.get();
                entity.setBaseBusinessIndicatorsId(baseIndicator.getId());
                List<BusinessProgress> businessProgresses = entity.getBusinessProgresses();
                if (CollectionUtil.isNotEmpty(businessProgresses)) {
                    List<BusinessIndicators> businessIndicators = baseIndicator.getBusinessIndicators();
                    businessProgresses.forEach(bus -> {
                        Optional<BusinessIndicators> optional = businessIndicators.stream().filter(m -> bus.getIndicatorsCodeId().equals(m.getDataSourceId())).findFirst();
                        if (optional.isPresent()) {
                            BusinessIndicators indicator = optional.get();
                            bus.setBusinessIndicatorsId(indicator.getId());
                            bus.setIndicatorsWeight(indicator.getIndicatorsWeight());
                            bus.setBaseline(indicator.getBaseline());
                            bus.setTarget(indicator.getTarget());
                            bus.setBasicTarget(indicator.getBasicTarget());
                        }
                    });
                }
                List<TaskProgress> taskProgresses = entity.getTaskProgresses();
                if (CollectionUtil.isNotEmpty(taskProgresses)) {
                    List<TaskIndicators> taskIndicators = baseIndicator.getTaskIndicators();
                    taskProgresses.forEach(task -> {
                        Optional<TaskIndicators> optional = taskIndicators.stream().filter(m -> task.getIndicatorsCodeId().equals(m.getDataSourceId())).findFirst();
                        if (optional.isPresent()) {
                            TaskIndicators indicator = optional.get();
                            task.setTaskIndicatorsId(indicator.getId());
                        }
                    });
                }
                List<MajorProgress> majorProgresses = entity.getMajorProgresses();
                if (CollectionUtil.isNotEmpty(majorProgresses)) {
                    List<MajorProject> majorProjects = baseIndicator.getMajorProjects();
                    majorProgresses.forEach(major -> {
                        Optional<MajorProject> optional = majorProjects.stream().filter(m -> major.getIndicatorsCodeId().equals(m.getDataSourceId())).findFirst();
                        if (optional.isPresent()) {
                            MajorProject majorProject = optional.get();
                            major.setMajorProjectId(majorProject.getId());
                        }
                    });
                }
                List<MainProgress> mainProgresses = entity.getMainProgresses();
                if (CollectionUtil.isNotEmpty(mainProgresses)) {
                    List<MainBusiness> mainBusinesses = baseIndicator.getMainBusinesses();
                    mainProgresses.forEach(main -> {
                        Optional<MainBusiness> optional = mainBusinesses.stream().filter(m -> main.getIndicatorsCodeId().equals(m.getDataSourceId())).findFirst();
                        if (optional.isPresent()) {
                            MainBusiness mainBusiness = optional.get();
                            main.setMainBusinessId(mainBusiness.getId());
                        }
                    });
                }
            }
        }
    }

}
